<template>
  <AppPage show-footer>
    <div position-absolute top-20 right-20 dark:color="#aaa">
      <ThemeMode />
    </div>
    <div m-auto max-w-700 min-w-345 f-c-c rounded-10 bg-white bg-opacity-60 p-15 card-shadow dark:bg-dark>
      <span m-x-60>
        <CustomIcon icon="wizard" :size="200" />
      </span>

      <div w-320 flex-col px-20 py-35>
        <h5 f-c-c text-24 font-normal color="#6a6a6a">
          <icon-custom-logo w-50 h-50 mr-10 text-50 color-red />
          {{ title }}
        </h5>
        <div mt-30>
          <n-input
            v-model:value="loginInfo.name"
            autofocus
            class="h-50 items-center pl-10 text-16"
            placeholder="用户名"
            :maxlength="20"
          />
        </div>
        <div mt-30>
          <n-input
            v-model:value="loginInfo.password"
            class="h-50 items-center pl-10 text-16"
            type="password"
            show-password-on="mousedown"
            placeholder="密码"
            :maxlength="20"
            @keypress.enter="handleLogin"
          />
        </div>

        <div mt-20>
          <n-checkbox :checked="isRemember" label="记住我" :on-update:checked="(val) => (isRemember = val)" />
        </div>

        <div mt-20>
          <n-button h-50 w-full rounded-5 text-16 type="primary" :loading="loading" @click="handleLogin">登录</n-button>
        </div>
      </div>
    </div>
  </AppPage>
</template>

<script setup lang="ts">
import api from '@/api'
import { useRequest } from 'alova'
import { addDynamicRoutes } from '@/router'
import { lStorage, setToken } from '@/utils'
import { useStorage } from '@vueuse/core'
import ThemeMode from '@/layout/components/header/components/ThemeMode.vue'

const title = import.meta.env.VITE_TITLE

const router = useRouter()
const { query } = useRoute()

const loginInfo = ref({
  name: '',
  password: ''
})

initLoginInfo()

function initLoginInfo() {
  const localLoginInfo = lStorage.get('loginInfo')
  if (localLoginInfo) {
    loginInfo.value.name = localLoginInfo.name || ''
    loginInfo.value.password = localLoginInfo.password || ''
  }
}

const isRemember = useStorage('isRemember', false)

const { loading, send } = useRequest((d) => api.login(d), {
  immediate: false
})

async function handleLogin() {
  const { name, password } = loginInfo.value
  if (!name || !password) {
    window.$message.warning('请输入用户名和密码')
    return
  }
  window.$message.loading('正在验证...')
  const { data } = await send({ name, password })
  window.$message.success('登录成功')
  setToken(data.token)
  if (isRemember.value) {
    lStorage.set('loginInfo', { name, password })
  } else {
    lStorage.remove('loginInfo')
  }
  await addDynamicRoutes()
  if (query.redirect) {
    const path = query.redirect as string
    Reflect.deleteProperty(query, 'redirect')
    router.push({ path, query })
  } else {
    router.push('/')
  }
}
</script>
